import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    // 这种写法是路由懒加载 提高加载速度
    // /* webpackChunkName: "about" */ 表示js文件分类打包
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
  }, {
    path: '/home',
    redirect: '/users',
    component: () => import('../views/Home.vue'),
    children: [
      {
        path: '/users',
        component: () => import('../views/Welcome.vue')
      },
      {
        path: '/roles',
        component: () => import('../views/authority/Roles.vue')
      },
      {
        path: '/rights',
        component: () => import('../views/authority/Rights.vue')
      },
      {
        path: '/goods',
        component: () => import('../views/commodity/Goods.vue')

      },
      {
        path: '/add',
        component: () => import('../views/commodity/Add.vue')
      },
      {
        path: '/categories',
        component: () => import('../views/commodity/Categories.vue')
      },
      {
        path: '/params',
        component: () => import('../views/commodity/Params.vue')
      },
      {
        path: '/orders',
        component: () => import('../views/orders/Orders.vue')
      }, {
        path: '/reports',
        component: () => import('../views/reports/Reports.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token') // 放在外面只会执行一次
  // if (to.path !== '/login') {
  //   if (token) {
  //     next()
  //   } else {
  //     next('/login')
  //   }
  // } else {
  //   if (token) {
  //     next('/home')
  //   } else {
  //     next()
  //   }
  // }
  if (to.path === '/login') return next()
  if (!token) return next('/login')
  next()
}
)

export default router
